package org.example.lethear.security;

import org.example.lethear.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Spring Security用户详情实现类
 */
public class UserDetailsImpl implements UserDetails {
    
    private final User user;
    private final Collection<? extends GrantedAuthority> authorities;
    
    public UserDetailsImpl(User user, Collection<? extends GrantedAuthority> authorities) {
        this.user = user;
        this.authorities = authorities;
    }
    
    /**
     * 从User实体创建UserDetailsImpl
     */
    public static UserDetailsImpl create(User user) {
        List<GrantedAuthority> authorities = user.getRoles().stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRoleName()))
                .collect(Collectors.toList());
        
        return new UserDetailsImpl(user, authorities);
    }

    
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }
    
    @Override
    public String getPassword() {
        return user.getPassword();
    }
    
    @Override
    public String getUsername() {
        return user.getUsername();
    }
    
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    
    @Override
    public boolean isAccountNonLocked() {
        return user.isEnabled();
    }
    
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    
    @Override
    public boolean isEnabled() {
        return user.isEnabled();
    }
    
    /**
     * 获取用户ID
     */
    public Long getId() {
        return user.getId();
    }
    
    /**
     * 获取用户邮箱
     */
    public String getEmail() {
        return user.getEmail();
    }
    
    /**
     * 获取用户实体
     */
    public User getUser() {
        return user;
    }
    
    /**
     * 检查是否有指定角色
     */
    public boolean hasRole(String roleName) {
        return authorities.stream()
                .anyMatch(authority -> authority.getAuthority().equals("ROLE_" + roleName));
    }
    
    /**
     * 检查是否为管理员
     */
    public boolean isAdmin() {
        return hasRole("ADMIN");
    }
} 